import IntersectionObserver from 'intersection-observer-polyfill';
import { useState, useEffect } from 'react';
window.IntersectionObserver = IntersectionObserver;
/**
 * 监听dom的显示隐藏hooks
 * @param target dom的ref实例
 * @param showCallBack dom显示的回调函数
 * @param hideCallBack dom隐藏的回调函数
 */
export const useDomAppear = (target, showCallBack, hideCallBack) => {
    const [state, setState] = useState({ isAppear: false, appearParsent: 0 });
    useEffect(() => {
        const io = new IntersectionObserver((entry) => {
            const { intersectionRatio } = entry[0];
            setState((prev) => {
                const isAppear = intersectionRatio > 0;
                if (prev.isAppear !== isAppear) {
                    if (isAppear) {
                        showCallBack?.();
                    }
                    else {
                        hideCallBack?.();
                    }
                }
                return {
                    isAppear,
                    appearParsent: intersectionRatio
                };
            });
        });
        io.observe(target.current);
        return () => {
            io.unobserve(target.current);
        };
    }, []);
    return state;
};
